import { CanActivate, ExecutionContext, Injectable } from '@nestjs/common';
import * as jwt from 'jsonwebtoken';
import config from 'src/config';
import AesUtils from 'src/utils/aes';
import { Server, Socket } from 'socket.io'

@Injectable()
export class SocketJwtGuard implements CanActivate {
    async canActivate(context: ExecutionContext) {
		let authorization=context.switchToWs().getClient().handshake.auth["Authorization"]
		if(!authorization){
			context.switchToWs().getClient().disconnect()
			return false;
		}
		let token = authorization.split(' ')[1];
		if(token){
			try {
				const jwtPayload:any=jwt.verify(token, config.app.secret);
				context.switchToWs().getData().userId = jwtPayload._id;
			} catch (error) {
				console.log(error)
				context.switchToWs().getClient().emit('message','无权限访问')
				context.switchToWs().getClient().disconnect()
				return false;
			}
			return true;
		}else{
			return false;
		}

    }
}

@Injectable()
export class SocketEncryptGuard implements CanActivate {
    async canActivate(context: ExecutionContext) {
		let body=context.getArgByIndex(1)
		if(body&&typeof body=='string'){
			try {
				//@ts-ignore
				context.args[1]=JSON.parse(body)
			} catch (error) {

			}
		}
		let data=context.switchToWs().getData()
		let apiSecret=context.switchToWs().getClient().handshake.headers["api-secret"]
		if(data&&data.data){
			if(config.env=="dev"||config.env=="pre"||config.env=="test"){
				if(apiSecret==="true"){
					let json=AesUtils.decryptToJson(data.data)
					context.switchToWs().getData().data=json;
				}
			}else{
				let json=AesUtils.decryptToJson(data.data)
				context.switchToWs().getData().data=json;
			}
		}
		return true
    }
}

export function encryptResponse(payload:any){
	if(config.env=="dev"||config.env=="pre"||config.env=="test"){
		if(payload.apiSecret){
			return AesUtils.encryptAes(payload.data)
		}else{
			return payload.data
		}
	}else{
		return AesUtils.encryptAes(payload.data)
	}
}
